package binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 10:23
 * https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
 * 给定一个非空二叉树的根节点 root , 以数组的形式返回每一层节点的平均值。与实际答案相差 10-5 以内的答案可以被接受。
 */
public class AverageOfLevels {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        Queue<TreeNode> levelNodes = new LinkedList<>();
        levelNodes.offer(root);
        while (!levelNodes.isEmpty()) {
            double temp = 0.0;
            int size = levelNodes.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = levelNodes.poll();
                temp += poll.val;
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
            temp /= size;
            result.add(temp);
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
